package com.jy.horny.function.editinfo

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import androidx.recyclerview.widget.GridLayoutManager
import com.jy.horny.ToastUtil
import com.jy.horny.adapter.RegisterPhotoAdapter
import com.jy.horny.base.BaseVMActivity
import com.jy.horny.databinding.ActivityEditProfileBinding
import com.jy.horny.dialog.EditNickNameDialog
import com.jy.horny.dialog.SelectBirthDialog
import com.jy.horny.dialog.UploadPhotoDialog
import com.jy.horny.model.PhotoModel
import com.jy.horny.utils.OpenAlbumCameraUtil
import com.lib.module_base.utils.StatusBarUtil
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.entity.LocalMedia

/**
 * 用户信息资料编辑页
 */
class EditProfileActivity : BaseVMActivity<ActivityEditProfileBinding, EditProfileViewModel>(
    ActivityEditProfileBinding::inflate,
    EditProfileViewModel::class.java
) {

    private var adapterPhoto: RegisterPhotoAdapter? = null
    private var photoSelectIndex: Int = 0
    private var imgList = arrayListOf(
        PhotoModel("", "", false),
        PhotoModel("", "", false),
        PhotoModel("", "", false),
        PhotoModel("", "", false),
        PhotoModel("", "", false),
        PhotoModel("", "", false)
    )

    override fun initData() {
        binding.titleEditProfile.setTitleText("Edit profile")
        binding.titleEditProfile.setTitleBarPadding(StatusBarUtil.getStatusBarHeight(this))
        initPhoto()
    }

    //初始化点击事件
    override fun initListener() {
        var parts: List<String>?
        var year: String? = null
        var month: String? = null
        var day: String? = null
        binding.imgEditProfileBirth.setOnClickListener {
            //获取年月日的值
            val txtBirth = binding.editProfileNickBirth.text.toString()
            if (!TextUtils.isEmpty(txtBirth)) {
                // 使用 split 函数进行字符串切割
                parts = txtBirth.split("-")
                month = parts!![0]
                day = parts!![1]
                year = parts!![2]
            }
            //点击修改出生日期
            SelectBirthDialog.Builder(this@EditProfileActivity)
                .setCallback(object : SelectBirthDialog.Callback {
                    override fun onBackClick(value: String?) {
                        binding.editProfileNickBirth.text = value
                    }
                }, month, day, year).show()
        }
        binding.imgEditProfileNickname.setOnClickListener {
            //点击昵称修改
            EditNickNameDialog.Builder(this@EditProfileActivity)
                .setCallback(object : EditNickNameDialog.Callback {
                    override fun onBackClick(name: String?) {
                        binding.editProfileNickName.text = name
                    }
                }, binding.editProfileNickName.text.toString()).show()
        }
    }

    //初始化图片
    private fun initPhoto() {
        binding.rvEditProfile.layoutManager = GridLayoutManager(this, 3)
        adapterPhoto = RegisterPhotoAdapter(object : RegisterPhotoAdapter.OnItemPhotoClickListener {
            override fun selectItemPhoto(url: String, position: Int) {
                photoSelectIndex = position
                UploadPhotoDialog.Builder(this@EditProfileActivity)
                    .setCallback(object : UploadPhotoDialog.Callback {
                        override fun onBackClick(type: Int?) {
                            if (type == 1) {
                                OpenAlbumCameraUtil.openAlbum(this@EditProfileActivity)
                            } else {
                                OpenAlbumCameraUtil.openCamera(this@EditProfileActivity)
                            }
                        }
                    }).show()
            }

            override fun deleteItemPhoto(url: String, position: Int) {
                imgList.removeAt(position)
                imgList.add(PhotoModel("", "", false))
                adapterPhoto?.getDataList()?.clear()
                adapterPhoto?.getDataList()?.addAll(imgList)
                adapterPhoto?.notifyDataSetChanged()
            }

        })
        adapterPhoto?.getDataList()?.addAll(imgList)
        binding.rvEditProfile.adapter = adapterPhoto
        adapterPhoto?.notifyDataSetChanged()
    }

    private fun addImage(selectList: ArrayList<LocalMedia>?) {
        selectList?.forEach {
            val path = when {
                it.isCompressed -> {
                    it.compressPath
                }

                it.isCut -> {
                    it.cutPath
                }

                else -> {
                    it.realPath
                }
            }
            if (path.contains(".mp4", true) || it.mimeType.contains(
                    ".3gp",
                    true
                ) || it.mimeType.contains(".mov", true)
            ) {
                ToastUtil.showToast("pls upload photo.")
                return
            }

            if (imgList[photoSelectIndex].imgUrl != "") {
                imgList[photoSelectIndex].imgUrl = ""
                imgList[photoSelectIndex].state = true
                adapterPhoto?.notifyItemChanged(photoSelectIndex)
            } else {
                for (i in 0 until imgList.size) {
                    if (imgList[i].imgHttpUrl == "" && !imgList[i].state) {
                        imgList[i].state = true
                        adapterPhoto?.notifyItemChanged(i)
                        break
                    }

                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    val selectList = PictureSelector.obtainSelectorList(data)
                    addImage(selectList)
                }
            }
        }
    }

    companion object {
        fun start(context: Context?) {
            context?.startActivity(Intent(context, EditProfileActivity::class.java))
        }
    }

}